package org.dna.metronomo.persistence;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import java.util.logging.Logger;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.ScriptRunner;

/**
 * Static inner class to verify and create DB schema
 * */
public class DBInit {

	private static final String DB_SCHEMA_PATH = "org/dna/metronomo/persistence/ddl/hsql/metronomo-schema.sql";

	public static String DRIVER;
	public static String USERNAME;
	public static String PASSWORD;
	public static String URL;
	
	private static boolean s_schemaInitialized;
	
	private static final Logger LOG = Logger.getLogger("org.dna.metronomo.persistence");

	private static void initScriptRunner(Connection conn) throws IOException {
		ScriptRunner runner = new ScriptRunner(conn);
		runner.setErrorLogWriter(null);
		runner.setLogWriter(null);

		runner.runScript(Resources.getResourceAsReader(DB_SCHEMA_PATH));
	}
	
	private synchronized static void createSchema(Connection conn) throws PersistenceException {
		if (s_schemaInitialized) {
			LOG.info("schema already created");
			return;
		}
		
//		Connection conn = null;
//		try {
//			conn = m_sqlSessionFactory.getConfiguration().getEnvironment()
//					.getDataSource().getConnection();
//		} catch (SQLException e) {
//			LOG.warning("Error retrieving the connection");
//			return;
//		}
		try {
			conn.createStatement().execute("SELECT * FROM User");
			LOG.info("database schema exists, normal startup");
		} catch (SQLException sqle) {
			LOG.warning("expected database schema does not exist, will "
					+ "create. Error is: " + sqle.getMessage());
			try {
				initScriptRunner(conn);
			} catch (IOException e) {
				LOG.warning("Error in creating DB schema" + e);
				throw new PersistenceException(e);
			}

			// create new admin User
			// LOG("inserting default admin user into database");
			LOG.info("schema creation complete");
		}
		s_schemaInitialized = true;
	}

	public static void createSchema() {
		try {
			Properties props = Resources
					.getResourceAsProperties("org/dna/metronomo/persistence/db.properties");
			URL = props.getProperty("url") + ":" + props.getProperty("db.type")
					+ ":" + props.getProperty("db.name");
			DRIVER = props.getProperty("driver");
			USERNAME = props.getProperty("username");
			PASSWORD = props.getProperty("password");
			// if (url.equals("jdbc:hsqldb:mem:jpetstore")) {
			Class.forName(DRIVER).newInstance();
			Connection conn = DriverManager.getConnection(URL, USERNAME,
					PASSWORD);

			try {
				createSchema(conn);
			} finally {
				conn.close();
			}
		} catch (Exception e) {
			throw new RuntimeException("Description.  Cause: " + e, e);
		}
	}
}
